<template>
  <canvas ref="colorSlider" width="260" height="24" @click="selectColor"></canvas>
</template>
<script setup lang="ts">
import { rgbToHex } from '@/utils/color';
const props = withDefaults(
  defineProps<{
    modelValue?: string; //颜色
  }>(),
  {
  },
);
// 定义 emits
const emit = defineEmits(['update:modelValue', 'change']);
// 更新 modelValue 的方法
const updateValue = (newValue: string) => {
  emit('update:modelValue', newValue);
  emit('change');
};
const colorSlider = ref(null)
const drawColorSlider = () => {
  const canvas: any = colorSlider.value
  const ctx = canvas.getContext('2d');
  if (!ctx) return;
  // 清除画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  var gradientH = ctx.createLinearGradient(0, 0, canvas.width, 0);
  var colors = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff']
  var evenDistribution = 1 / colors.length
  colors.forEach((el: any, index: any) => {
    gradientH.addColorStop(evenDistribution * index, el); // 设置一定的透明度
  })
  gradientH.addColorStop(1, colors[0]); // 设置一定的透明度
  ctx.fillStyle = gradientH;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}
const selectColor = (event: any) => {
  const canvas: any = colorSlider.value
  const ctx = canvas.getContext('2d');
  if (!ctx) return;
  // 获取点击位置相对于 canvas 的坐标
  const rect = canvas.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  const pixelData = ctx.getImageData(x, y, 1, 1).data;
  const [r, g, b, a] = pixelData;
  const rgb = { r, g, b }
  const hex = rgbToHex(rgb);
  updateValue(hex)
}

onMounted(() => {
  drawColorSlider()
});

onBeforeUnmount(() => { });
</script>
<style scoped lang="scss"></style>